# -*- coding: utf-8 -*-
import asyncio
import logging

from pyppeteer import launch
from scrapy.utils.project import get_project_settings
from zc_core.middlewares.proxies.cached_pool import CachedProxyPool
from ctaxccgp.simple.bak.simple_dao import SimpleDao
from ctaxccgp.simple.bak.simple_session import SimpleSession

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    filename='order_list_ios.log',
    filemode='a')
console = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)

# 登录会话管理
simple_session = SimpleSession()
cookies = {'JSESSIONID': '5A4A65598E15B8EE363B0B3E0D0D9D1A'}

# 构建校验器对象
settings = get_project_settings()
proxy_pool = CachedProxyPool(settings)
simple_dao = SimpleDao()
max_retry = 5
batch_retry_map = {}

item_url_tpl = 'https://ctaxccgp.zcygov.cn/items/{}'
# browser = await launch(headless=False, userDataDir='E:/TempData/', ignoreDefaultArgs=['--enable-automation'])


# width, height = 1366, 768
# browser = await pyppeteer.launch(
#     headless=False,
#     # headless=True,
#     timeout=1500,
#     # 开发者工具
#     devtools=False,
#     dumpio=True,
#     options={'args':
#         [
#             '--no-sandbox',
#             # 关闭提示条
#             '--disable-infobars',
#             f'--window-size={width},{height}',
#             '--disable-extensions',
#             '--hide-scrollbars',
#             '--disable-bundled-ppapi-flash',
#             '--mute-audio',
#             '--disable-setuid-sandbox',
#             '--disable-gpu',
#         ],
#     }
# )
# 无痕模式浏览器
# context = await self.browser.createIncogniteBrowserContext()
# self.page = await context.browser.newPage()


# def init_tasks(batch_no):
#     rows = simple_dao.get_batch_data(batch_no)
#     for row in rows:
#         sku_id = row['_id']
#         open_page(sku_id)


async def open_page(sku_id):
    browser = await launch(headless=False, userDataDir='E:/TempData/', ignoreDefaultArgs=['--enable-automation'])
    page = await browser.newPage()
    url = item_url_tpl.format(sku_id)
    await page.goto(url)
    await page.waitForSelector('div#tab-dealrecord')
    await asyncio.sleep(1.2)
    await page.click('div#tab-dealrecord')
    await asyncio.sleep(1)
    await page.reload()
    await page.waitForSelector('div#tab-dealrecord')
    await asyncio.sleep(1.3)
    await page.click('div#tab-dealrecord')
    await asyncio.sleep(2)
    print(page.plainText())
    # await browser.close()


if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(open_page('18636828'))
    # asyncio.get_event_loop().run_until_complete(init_tasks())
